import React, { useEffect, useRef, useState } from "react";
import { Button, Checkbox, Form, Input, Row, Col, message } from "antd";
import { getCaptchaApi, userLoginApi, getUserByIdApi } from "@/api/user.js";
import "../index.scss";
import { initUserInfo, changeLoginStatus } from "@/redux/userSlice";
import { useDispatch } from "react-redux";
/**
 * 登录表单
 */
export default function Login(props) {
  const loginFormRef = useRef();
  const dispatch = useDispatch();
  const [captcha, setCaptcha] = useState(null);
  const [loginInfo, setLoginInfo] = useState({
    loginId: "",
    loginPwd: "",
    captcha: "",
    remember: false,
  });

  /**
   * 统一更新登录数据
   * @param {*} oldInfo  原来的数据
   * @param {*} newInfo  新的数据
   * @param {*} key      更新那个数据
   * @param {*} setLoginInfo 函数
   */
  const update = (oldInfo, newInfo, key, setLoginInfo) => {
    const obj = { ...oldInfo };
    obj[key] = newInfo;
    setLoginInfo(obj);
  };

  const handleClickCaptcha = () => {
    (async () => {
      const res = await getCaptchaApi();
      setCaptcha(res);
    })();
  };

  useEffect(() => {
    handleClickCaptcha();
  }, [props.isModalOpen]);

  const clearConent = () => {
    setLoginInfo({
      loginId: "",
      loginPwd: "",
      captcha: "",
      remember: false,
    });
    props.onClose();
  };
  const onFinish = async (values) => {
    const res = await userLoginApi(values);
    if (!res.data) {
      // 验证码错误 -> 刷新验证码
      message.error(res.msg);
      handleClickCaptcha();
    } else {
      // 验证码正确 （1）用户名/密码正确？（2）是否被禁用（3）正常信息
      if (!res.data.data) {
        // 用户名或密码错误
        message.error("用户名或密码错误");
      } else if (!res.data.data.enabled) {
        // 被禁用
        message.warning("账号被禁用，请联系管理员");
      } else {
        // 正常登录 -> 通过_id获得用户信息 -> 存入数据仓库 & 改变登录状态 -> 存token -> 移除信息 & 关闭Modal -> 提示登录成功
        const result = await getUserByIdApi(res.data.data._id);
        dispatch(initUserInfo(result.data));
        dispatch(changeLoginStatus(true));
        localStorage.setItem("token", res.data.token);
        clearConent();
        message.success("登录成功");
      }
    }
  };

  return (
    <>
      <Form
        name="login"
        onFinish={onFinish}
        autoComplete="off"
        style={{ width: "450px", margin: "20px auto" }}
        ref={loginFormRef}
      >
        <Form.Item
          label="登录账号："
          name="loginId"
          rules={[
            { required: true, message: "请输入账号" },
            { min: 3, max: 10, message: "账号长度不能小于3位，不能大于10位" },
          ]}
        >
          <Input
            placeholder="请输入你的登录账号"
            value={loginInfo.loginId}
            onChange={(e) => update(loginInfo, e.target.value, "loginId", setLoginInfo)}
          />
        </Form.Item>

        <Form.Item
          label="登录密码："
          name="loginPwd"
          rules={[
            { required: true, message: "请输入密码" },
            { min: 6, message: "密码长度不能小于6" },
          ]}
        >
          <Input.Password
            placeholder="请输入你的登录密码，新用户默认为123456"
            value={loginInfo.loginPwd}
            onChange={(e) => update(loginInfo, e.target.value, "loginPwd", setLoginInfo)}
          />
        </Form.Item>

        <Form.Item
          label="验证码："
          name="captcha"
          rules={[
            { required: true, message: "请输入验证码" },
            {
              validator: (_, value) => {
                let reg = /^[^\u4e00-\u9fa5]+$/g;
                if (!value) {
                  return Promise.resolve();
                }
                if (!reg.test(value)) {
                  return Promise.reject("只能输入数字或字母");
                }
                return Promise.resolve();
              },
            },
          ]}
        >
          <Row align="middle">
            <Col span={16}>
              <Input
                placeholder="请输入验证码"
                value={loginInfo.captcha}
                onChange={(e) => update(loginInfo, e.target.value, "captcha", setLoginInfo)}
              />
            </Col>
            <Col span={6}>
              <div
                className="captchaImg"
                dangerouslySetInnerHTML={{ __html: captcha }}
                onClick={handleClickCaptcha}
              ></div>
            </Col>
          </Row>
        </Form.Item>

        <Form.Item name="remember" valuePropName="checked" label={null} style={{ marginLeft: 10 }}>
          <Checkbox
            checked={loginInfo.remember}
            onChange={(e) => update(loginInfo, e.target.value, "remember", setLoginInfo)}
          >
            记住我
          </Checkbox>
        </Form.Item>

        <Form.Item label={null}>
          <Button type="primary" htmlType="submit" style={{ marginRight: 20 }}>
            登录
          </Button>
          <Button type="primary" htmlType="reset">
            重置
          </Button>
        </Form.Item>
      </Form>
    </>
  );
}
